<template>
	<view class="confirm-order">
		<view class="confirm-bg"></view>
		<view class="inner" v-if="goods!=''">
			<view class="dizhi"  @tap="toAddress">
				<image src="https://farm-city.oss-cn-hangzhou.aliyuncs.com/static/order/dingwei.png" mode="widthFix" class="dingwei-img"/>
				<view class="right">
					<view class="right-left" v-if="add!='' && add!=null">
						<view class="right-left-top">
							<text>{{add.consignee}}</text>
							<text class="phone">{{add.mobile}}</text>
						</view>
						<view class="right-left-bot">{{add.province+add.city+add.district+add.address}}</view>
					</view>
					<view class="right-add" v-else>添加收货地址</view>
					<image src="https://farm-city.oss-cn-hangzhou.aliyuncs.com/static/common/more-grey.png" mode="widthFix" class="more-img">
				</view>
			</view>
			<view class="confirm-order-goods shop-confirm-order-goods">
				<view class="confirm-order-goods-logo">
					<image :src="store_info.wap_login_logo" mode="widthFix"/>
					<text>{{store_info.store_title}}</text>
				</view>
				<view class="order-goods-items">
					<view class="order-goods-item">
						<image :src="goods.goods_img" class="goods-img"></image>
						<view class="right">
							<view class="goods-name">{{goods.goods_name}}</view>
							<view class="goods-bot">
								<view class="goods-bot-left">
									<text>¥</text>
									<text class="large">{{goods.goods_price}}</text>
								</view>
								<view class="goods-bot-right">
									<text :class="{'dis':form.goods_num<=1}" @click="addAndSubtract(goods,-1)">-</text>
									<text>{{form.goods_num}}</text>
									<text :class="{'dis':form.goods_num>=goods.store_count}" @click="addAndSubtract(goods,1)">+</text>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="rows">
					<view class="row">
						<view class="left">小计</view>
						<view class="right">¥{{total_amount}}</view>
					</view>
				</view>
			</view>
			<view class="goods-row">
				<view class="goods-row-tit">备注</view>
				<u-input border="none" class="body_phone_input" placeholder="请填写备注信息(选填)"
					placeholderClass="input-placeholder" type="text" fontSize="26rpx" clearable v-model="form.user_note">
				</u-input>
				<view style="height: 20rpx;"></view>
			</view>
			<view class="goods-row">
				<view class="goods-row-tit">请选择支付方式</view>
				<view class="pay-items">
					<view @tap="changePay(item.code)" class="pay-item" v-for="(item,index) in pay_list" :key="index">
						<image mode="widthFix" src="https://farm-city.oss-cn-hangzhou.aliyuncs.com/static/order/zf-money.png" class="pay-item-left-img"/>
						<text>{{item.name}}</text>
						<image mode="widthFix" :src="form.pay_code==item.code?'https://farm-city.oss-cn-hangzhou.aliyuncs.com/static/common/checkbox-sel.png':'https://farm-city.oss-cn-hangzhou.aliyuncs.com/static/common/checkbox.png'" class="pay-item-img"/>
					</view>
				</view>
			</view>
			<view style="height: 120rpx;"></view>
		</view>
		<view class="confirm-order-bot" v-if="goods!=''">
			<view class="left">
				<text>合计:</text>
				<text class="amount">{{amount}}</text>
				<text>元</text>
			</view>
			<button type="default" class="zf-btn" :disabled="btnDisabled" @click="tijiao()">立即支付</button>
		</view>
		<u-popup
		:show="showPaypwd" 
		mode="center" 
		:customStyle="{'width':'80%'}"
		round="5"
		:closeOnClickOverlay="false"
		:overlayOpacity="0.6">
			<view class="paypwd-container">
				<image src="https://farm-city.oss-cn-hangzhou.aliyuncs.com/static/common/close.png" mode="widthFix" class="close-img" @click="showPaypwd=false"></image>
				<view class="title">交易密码</view>
				<view class="form-rows">
					<u-input border="none" class="row-input" placeholder="请填写交易密码"
						placeholderClass="input-placeholder" type="password" fontSize="26rpx" clearable v-model="form.paypwd">
					</u-input>
				</view>
				<view class="btn-container">
					<button class="con-btn" @click="queding" :disabled="btnDisabled">确认</button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	var validate = require("@/components/validate/validate.js");
	var _this;
	export default {
		data() {
			return {
				form:{
					step:1,
					address_id:0,
					goods_num:1,
					goods_id:0,
					pay_code: '',
					item_id: 0,
					pay_code: '',
					user_note: '',
					paypwd: '',
					order_id: 0,
				},
				showPaypwd:false,
				store_info:'',
				show:false,
				add: '',
				goods: '',
				pay_list: [],
				pay_code: '',
				name: '',
				temp_ship_price:0,
				btnDisabled:false
			}
		},
		onLoad(e) {
			_this=this
			if(e.id){
				_this.form.goods_id=e.id
			}
			if(e.goods_num){
				_this.form.goods_num=e.goods_num
			}
			this.get_confirm()
			uni.$on('chooseAddress',res=>{
				_this.form.address_id=res
				_this.getaddress()
			})
		},
		onUnload() {
			uni.$off('chooseAddress')
		},
		computed:{
			amount:{
				cache:false,
				get(){
					if(_this.goods==''){
						return 0.0
					}
					return _this.goods['goods_price']*_this.form.goods_num
				}
			},
			total_amount:{
				cache:false,
				get(){
					if(_this.goods==''){
						return 0.0
					}
					return _this.goods['goods_price']*_this.form.goods_num
				}
			}
		},
		methods: {
			addAndSubtract(item,num){
				if (num<0) {
					if(_this.form.goods_num+num<1){
						return
					}
					--_this.form.goods_num
				}else{
					if(_this.form.goods_num+num>item.store_count){
						return
					}
					++_this.form.goods_num
				}
			},
			// 输入金额方法
			checkNum(e) {
			    let val = e+''.replace(/(^\s*)|(\s*$)/g, "")
				if(val<=0){
					this.$nextTick(() => {
					    this.use_jinbi = '';
					})
					return
				}
			    if (!val) {
			        this.$nextTick(() => {
			            this.use_jinbi = '';
			        })
			        return
			    }
				if(val>this.user_jinbi){
					this.$nextTick(() => {
					    this.use_jinbi = this.user_jinbi;
					})
					return
				}
			    var reg = /[^\d.]/g
			    // 只能是数字和小数点，不能是其他输入
			    val = val.replace(reg, "")
			    // // 保证第一位只能是数字，不能是点
			    val = val.replace(/^\./g, "");
			    // // 小数只能出现1位
			    val = val.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
			    // // 小数点后面保留2位
			    val = val.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
				val = (val.match(/^\d*(\.?\d{0,2})/g)[0]) || ''
			    // console.log(val);
			    this.$nextTick(() => {
			        this.use_jinbi = val;
			    })
			},
			//跳转到地址列表
			toAddress(){
				this.$u.route({
					url:'pages/center/address-list',
					params: {
						is_cart:1
					}
				})
			},
			//获取地址数据
			async getaddress(){
				const params = {
					address_id:this.form.address_id
				}
				const data = await _this.$post('api/Address',params)
				if(data.code==200){
					this.add = data.data.address
				}else{
					uni.$u.toast(data.msg)
					setTimeout(()=>{
						uni.navigateBack({})
					},2000)
				}
			},
			//切换支付方式
			changePay(code){
				if(this.form.pay_code==code){
					return;
				}
				this.form.pay_code=code
			},
			tijiao(){
				_this.showPaypwd=true
			},
			queding(){
				let rule = [
					{
						name: 'paypwd',
						rules: ['require', 'min:6'],
						errorMsg: {
							require: '请输入交易密码',
							min: '交易密码最少6位'
						}
					}
				]
				let check = validate.check(this.form,rule);
				if (!check) {
					// 获取错误信息
					let err = validate.getError();
					uni.$u.toast(err[0])
					return
				}
				_this.form.step=2
				_this.get_confirm()
			},
			//获取订单生成初始数据
			async get_confirm() {
				if(_this.form.step==2){
					_this.btnDisabled=true
					setTimeout(()=>{
						_this.btnDisabled=false
					},2000)
				}
				const data = await _this.$post('api/add_jifen_order',_this.form)
				if(data.code==100){
					uni.$u.toast(data.msg)
					setTimeout(()=>{
						uni.navigateBack({})
					},2000)
				}else if(data.code==-100){
					uni.$u.toast(data.msg)
					setTimeout(()=>{
						uni.$u.route({
							url:'pages/center/paypwd',
							type:'redirectTo'
						})
					},2000)
				}else if(data.code==200){
					uni.$u.toast(data.msg)
					setTimeout(()=>{
						uni.navigateBack({})
					},2000)
					// setTimeout(()=>{
					// 	uni.$u.route({
					// 		url:'pages/order/order-list',
					// 		type:'redirectTo',
					// 		params:{
					// 			status:2
					// 		}
					// 	})
					// },2000)
				}else if(data.code==10){
					this.add = data.data.add
					if(this.add){
						this.form.address_id=this.add.address_id
						this.getaddress()
					}
					this.goods = data.data.goods
					this.pay_list = data.data.pay_list
					this.form.pay_code=this.pay_list[0]['code']
					this.temp_ship_price = data.data.ship_price
					this.name = data.data.name
					this.store_info = data.data.store_info
				}else if(data.code==30){
					//唤起微信支付
					uni.requestPayment({
					    provider: 'wxpay',
						timeStamp: data.data.result.timeStamp+'',
						nonceStr: data.data.result.nonceStr,
						package: data.data.result.package,
						signType: data.data.result.signType,
						paySign: data.data.result.sign,
						success: function (res) {
							_this.$u.toast('支付成功')
							setTimeout(()=>{
								uni.$u.route({
									url:'pages/order/order-list',
									type:'redirectTo',
									params:{
										status:2
									}
								})
							},2000)
						},
						fail: function (err) {
							console.log('fail:' + JSON.stringify(err));
						}
					});
				}else{
					uni.$u.toast(data.msg)
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import "@/static/css/order.scss";
</style>